<template>
  <div class="app-container">
    <div class="head-container">
      <!--搜索框-->
      <el-form inline :model="searchForm">
         <el-form-item>
            <el-input
                v-model="searchForm.username"
                placeholder="名称"
                clearable>
            </el-input>
         </el-form-item>
         <el-form-item>
            <el-button @click="getUserList()">搜索</el-button>
            <el-button type="primary" @click="dialogFormVisible = true" v-permission="['sys:role:save']">新增</el-button>
            <el-popconfirm title="确定要删除这些记录吗？" @confirm="delHandle(null)" style="margin-left: 10px;">
              <template #reference>
                <el-button type="danger" :disabled="multipleSelection.length === 0" v-permission="['sys:role:delete']">批量删除</el-button>  
              </template>
            </el-popconfirm>
         </el-form-item>
      </el-form>
    </div>
    <el-table
      ref="table"  
      :data="data" 
      :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
      row-key="id"
      stripe
      default-expand-all
      style="width: 100%;"
      @selection-change="handleSelectionChange">
        <el-table-column type="selection" />
        <el-table-column prop="avatar" label="头像">
          <template #default="scope">
            <el-avatar size="small" :src="scope.row.avatar" />
          </template>
        </el-table-column>
        <el-table-column prop="username" label="用户名" />
        <el-table-column label="角色名称">
          <template #default="scope">
            <el-tag style="margin-right: 5px;" size="small" type="info" v-for="item in scope.row.sysRoles" :key="item">{{item.name}}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="email" label="邮箱" />
        <el-table-column prop="phone" label="手机号" />
        <el-table-column prop="remark" label="状态">
          <template #default="scope">
              <el-tag v-if="scope.row.statu === 0" size="small" type="danger">禁用</el-tag>
              <el-tag v-else-if="scope.row.statu === 1" size="small" type="success">正常</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="created" label="创建时间" width="200" />
        <el-table-column prop="name" label="操作" width="300px">
          <template #default="scope">
            <el-button  size="small" @click="roleHandle(scope.row.id)"  v-permission="['sys:role:perm']">分配角色</el-button>
            <el-button  size="small" @click="repassHandle(scope.row.id, scope.row.username)"  v-permission="['sys:user:repass']">重置密码</el-button>
            <el-button size="small" type="primary" @click="editHandle(scope.row.id)"  v-permission="['sys:menu:update']">编辑</el-button>
            <el-popconfirm title="确定要删除这条记录吗？" @confirm="delHandle(scope.row.id)">
              <template #reference>
                <el-button 
                  type="danger"
                  icon="el-icon-delete"
                  size="small"
                  v-permission="['sys:menu:delete']"
                >
                  删除
                </el-button>
              </template>
            </el-popconfirm>
          </template>
      </el-table-column>
    </el-table>
    <!--页码-->
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="searchForm.current"
      :page-size="searchForm.size"
      layout="total, prev, pager, next, sizes"
      :total="total" 
    />
  </div>
  <!--编辑对话框-->
  <el-dialog title="用户信息" v-model="dialogFormVisible" width="600px">
    <el-form :model="editForm" :rules="editFormRules" ref="editFormRef">
      <el-form-item label="用户名" prop="username" label-width="100px">
        <el-input v-model="editForm.username" autocomplete="off" />
        <el-alert
          title="初始密码为123456"
          :closable="false"
          type="info"
          style="line-height: 12px;"
        ></el-alert>
      </el-form-item>
      <el-form-item label="邮箱" prop="email" label-width="100px">
        <el-input v-model="editForm.email" autocomplete="off" />
      </el-form-item>
      <el-form-item label="手机号" prop="phone" label-width="100px">
        <el-input v-model="editForm.phone" autocomplete="off" />
      </el-form-item>
      <el-form-item label="状态" prop="statu" label-width="100px">
          <el-radio-group v-model="editForm.statu">
            <el-radio :label="0">禁用</el-radio>
            <el-radio :label="1">正常</el-radio>
          </el-radio-group>
      </el-form-item>
      <div class="dialog-footer">
        <el-button @click="resetForm(editFormRef)">取 消</el-button>
        <el-button type="primary" @click="submitEditForm(editFormRef)">确 定</el-button>
      </div>
    </el-form>
  </el-dialog>
  <!-- 分配权限对话框 -->
  <el-dialog title="分配角色" v-model="roleDialogFormVisible" width="600px">
    <el-form :model="roleForm" ref="roleFormRef">
      <el-tree
            :data="roleTreeData"
            show-checkbox
            ref="roleTree"
            node-key="id"
            :default-expand-all=true
            :props="defaultProps">
      </el-tree>
    </el-form>
    <div class="dialog-footer">
      <el-button @click="resetForm(roleFormRef)">取 消</el-button>
      <el-button type="primary" @click="submitRoleForm(roleFormRef)">确 定</el-button>
    </div>
  </el-dialog> 
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue';
import { list, add, edit, info, del, role, repass } from "@/api/system/sysUser"
import { rolelist } from "@/api/system/role"
import { ElMessage, ElTable, FormInstance, ElTree, ElMessageBox  } from 'element-plus'




const data = ref([])
const searchForm = reactive({
  username: '',
  current: 1,
  size: 10
})
const total = ref()
function getUserList() {
  list(searchForm).then(res => {
    data.value = res.data.records
    searchForm.current = res.data.current
    searchForm.size = res.data.size
    total.value = res.data.total
  })
}
function handleSizeChange(val: any) {
  searchForm.size = val
  getUserList()
}
function handleCurrentChange(val: any) {
  searchForm.current = val
  getUserList()
}

const editFormRef = ref<FormInstance>()
const dialogFormVisible = ref(false)
const editForm = ref({} as UserDto)
const editFormRules = reactive({
    username: [
      {required: true, message: '请输入用户名称', trigger: 'blur'}
    ],
    email: [
      {required: true, message: '请输入邮箱', trigger: 'blur'}
    ],
    statu: [
      {required: true, message: '请选择状态', trigger: 'blur'}
    ]
})
function editHandle(id: string) {
  info(id).then(res => {
    editForm.value = res.data
    dialogFormVisible.value = true
  })
}
function submitEditForm(formEl: FormInstance | undefined) {
  if (!formEl) return
  formEl.validate(async (valid, fields) =>{
    if(valid) {
      try {
        editForm.value.id? await edit(editForm.value):add(editForm.value)
        ElMessage.success(`${editForm.value.id? '编辑': '添加'}成功 `)
        getUserList()
        dialogFormVisible.value = false
      } finally {
        dialogFormVisible.value = false
      }
    }
  })
}
function resetForm(formEl: FormInstance | undefined) {
  if (!formEl) return
  formEl.resetFields()
  dialogFormVisible.value = false
  roleDialogFormVisible.value = false
}

const multipleSelection = ref<UserDto[]>([])
const handleSelectionChange = (val: []) => {
  multipleSelection.value = val
  console.log(val)
} 
async function delHandle(id: string) {
  const ids = []
  id ? ids.push(id) : multipleSelection.value.forEach(item => {
    ids.push(item.id)
  });
  try {
    await del(ids)
    getUserList()
    ElMessage.success('删除成功')
  } catch (error) {
    console.log(error)
  }
}

const roleDialogFormVisible = ref(false)
const roleFormRef = ref<FormInstance>()
const roleTreeData = ref([])
const roleForm  = ref()
const roleTree = ref<InstanceType<typeof ElTree>>()
const treeCheckedKeys = ref([])
const defaultProps = {
  children: 'children',
  label: function(data: any, node: any) {
    return data.name
  },
}
function roleHandle(id: string) {
  info(id).then(res => {
    var roleIds: any[] = []
    roleForm.value = res.data
    res.data.sysRoles.forEach((row: any) => {
      roleIds.push(row.id)
    });
    rolelist().then(res => {
      roleTree.value!.setCheckedKeys(roleIds)
      roleTreeData.value = res.data.records
    })
  })
  roleDialogFormVisible.value = true
}
async function submitRoleForm(formEl: FormInstance | undefined) {
  var roleIds: any[] = []
  roleIds = roleTree.value!.getCheckedKeys()
  try {
    await role(roleForm.value.id, roleIds)
    ElMessage.success('操作成功')
    getUserList()
    resetForm(formEl)
    roleDialogFormVisible.value = false
  } finally {
    roleDialogFormVisible.value = false
  }
}

function repassHandle(id: number, username: string) {
  ElMessageBox.confirm('将重置用户【' + username + '】的密码, 是否继续?','提示',{
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(async () => {
    try {
      await repass(id)
      ElMessage.success('操作成功')
    } catch (error) {
      
    }
  })
}


onMounted(() => {
  getUserList()
})
</script>

<style lang="scss" scoped>
.dialog-footer {
  display: flex;
  justify-content: center;
}
</style>